package com.gainloop;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCException;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.*;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


import com.gainloop.R;
import com.gainloop.Api.ApiResponseObject;
import com.gainloop.Api.Users;
import com.gainloop.Api.Wishes;
import com.gainloop.Api.Entity.User;
import com.gainloop.Api.Entity.WishEx;
import com.gainloop.Data.Registry;
import com.gainloop.Utils.Constants;
import com.gainloop.Utils.Constants.ListType;
import com.gainloop.Utils.ImageThreadLoader;
import com.gainloop.Utils.ImageThreadLoader.ImageLoadedListener;

public class WishList extends ListActivity {
	private ArrayList<WishEx> wishes = null;
	private WishAdapter adapter;
	private Runnable viewWishes;
	private ProgressDialog progressDialog = null;
	private ListType listType;
	private User user;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wish_list);

		adapter = new WishAdapter(this, R.layout.wish_item, new ArrayList<WishEx>());

		setListAdapter(adapter);
		listType = (ListType)getIntent().getExtras().get(Constants.listTypeParam);
		Long userId=(Long)getIntent().getExtras().get(Constants.userParam);
		ApiResponseObject<User> resp=null;
		Users users=new Users();
		
		if (getIntent().hasExtra(Constants.userParam)){
			try {
				resp=users.getById(userId);
			} catch (JSONRPCException e) {
				e.printStackTrace();
				throw new RuntimeException();
			}
			if (resp.getReturnCode()==0){
				user=resp.getData();
			}	
			else{
				//could not get user from server.
				throw new RuntimeException(""+R.string.server_error+ resp.getReturnCode());
			}
			
		}
		else{
			user=Registry.GetUser();
		}
		
		viewWishes = new Runnable() {
			@Override
			public void run() {
				getWishes();
			}
		};
		Thread thread = new Thread(null, viewWishes, "MagentoBackground");

		//FIXME there is a problem with the processDialog when we can't
		//login to facebook.
		
		progressDialog = ProgressDialog.show(WishList.this, getString(R.string.wait_msg),
				getString(R.string.ret_data_msg), true);
		thread.start();

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				WishEx wish=adapter.getItem(position);
				//Toast.makeText(getApplicationContext(), "Wish Id: "+wish.getId(),
						//Toast.LENGTH_SHORT).show();

				Intent intent=new Intent(WishList.this,GainPage.class)
					.putExtra(GainPage.GAIN_ID, wish.getId());
				WishList.this.startActivity(intent);
				
			}

			
		});

	}

	private void getWishes() {
		try {
			
			switch (listType){
			case TOP:
				
				wishes = Wishes.getInstance().getTopWishes(1);
				break;
			case RECENT:
				wishes = Wishes.getInstance().getRecentWishes(1);
				break;
			case FRIENDS:
				wishes = Wishes.getInstance().getFriendsWishes(1);
				break;
			default:
				// TODO get which user from intent parameter
				Log.v("user.getId=",Long.toString(user.getId()));
				wishes = Wishes.getInstance().getUserWishes(user, 1);
				
				break;
				
			}
			
			
		} catch (JSONRPCException e) {
			wishes = new ArrayList<WishEx>();
			e.printStackTrace();
		}
		
		runOnUiThread(returnRes);
	}

	private class WishAdapter extends ArrayAdapter<WishEx> {

		private ArrayList<WishEx> items;

		public WishAdapter(Context context, int textViewResourceId,
				ArrayList<WishEx> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.wish_item, null);
			}
			WishEx item = items.get(position);
			if (item != null) {
				final ImageView profile = (ImageView) v
						.findViewById(R.id.wishItemProfileImg);
				TextView content = (TextView) v
						.findViewById(R.id.wishItemContent), username = (TextView) v
						.findViewById(R.id.wishItemUsername), category = (TextView) v
						.findViewById(R.id.wishItemCategory), helps = (TextView) v
						.findViewById(R.id.wishItemHelps);

				try {
//					URL newurl = new URL(
//							"http://graph.facebook.com/" + item.getUserFbId() + "/picture?type=square");
//					Bitmap bitmap = BitmapFactory.decodeStream(newurl
//							.openConnection().getInputStream());
//					profile.setImageBitmap(bitmap);
					
					Bitmap cachedImage = ImageThreadLoader.GetInstance().loadImage("http://graph.facebook.com/" + item.getUserFbId() + "/picture?type=square", 
							new ImageLoadedListener() {
						public void imageLoaded(Bitmap imageBitmap) {
							profile.setImageBitmap(imageBitmap);
							notifyDataSetChanged();                
						}
					});
					if(cachedImage != null)
						profile.setImageBitmap(cachedImage);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}

				username.setText(item.getUserName());
				content.setText(item.getContentShort());
				category.setText(item.getCategoryName());
				helps.setText("" + item.getHelpsNum());
			}
			return v;
		}
	}

	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			Log.v("loading", "strat insert");
			if (wishes != null && wishes.size() > 0) {
				adapter.notifyDataSetChanged();
				
				for (int i = 0; i < wishes.size(); i++){
					adapter.add(wishes.get(i));
				}
			}
			progressDialog.dismiss();
			adapter.notifyDataSetChanged();
		}
	};

}